package com.baizhi.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import cn.hutool.captcha.LineCaptcha;
import com.baizhi.entity.Admin;
import com.baizhi.service.AdminService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("admin")
@Slf4j
public class AdminController {
    @Autowired
    private AdminService adminService;
    @RequestMapping("getCaptcha")
    public void getCaptcha(HttpServletResponse response,HttpSession session)throws Exception{
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(80, 30);
        //获取session
        session.setAttribute("realCode", captcha);
        System.out.println(captcha.getCode());
        //使用一个输出流把验证码输出到html界面的src中
        captcha.write(response.getOutputStream());
    }
    @RequestMapping("login")
    public String login(String username,String password,String code){
        //        1.将页面用户输入的账号密码 封装到token中
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
//        2.获取Subject
        Subject subject = SecurityUtils.getSubject();
        /**
         *  subject.getSession()
         */
        Session subjectSession = subject.getSession();
        ICaptcha captcha = (ICaptcha) subjectSession.getAttribute("realCode");
        System.out.println("shiro的Session中获取的："+captcha.getCode());

//        3.使用Subject的认证方法完成认证
        try {
            subject.login(token);
            System.out.println("认证成功");

            return "redirect:/main.jsp";
        }catch (Exception e){
            System.out.println("认证失败");
            return "redirect:/login.jsp";
        }
    }
    @RequestMapping("selectAll")
    @ResponseBody
    public Map selectAll(Integer page,Integer limit){
        Map map = new HashMap();
        PageInfo<Admin> pageInfo = adminService.selectAll(page, limit);
        map.put("code",0);
        map.put("msg","");
        map.put("count",pageInfo.getTotal());
        map.put("data",pageInfo.getList());
        return map;
    }
    @RequestMapping("addAdmin")
    @ResponseBody
    public Map addAdmin(String username,String password){
        Map map = new HashMap();
        try {
            adminService.insert(username,password);
            map.put("flag",true);
        } catch (Exception e) {
            map.put("flag",false);
            e.printStackTrace();
        }
        return map;
    }



}
